/**
 * 
 */
package com.ws.framework.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.ws.framework.dao.UserDao;
import com.ws.framework.model.Role;
import com.ws.framework.model.User;

/**
 * <p>
 * </p>
 *
 * @author WSH
 */
@Repository
public class UserDaoImpl implements UserDao {

	//user_name不存在则插入
	private static final String insertUserSql = "INSERT INTO t_user(user_name,pwd,create_time) SELECT ?, ?, NOW() FROM DUAL WHERE NOT EXISTS (SELECT * FROM t_user WHERE user_name = ?);";

	//根据userName进行查询
	private static final String selectUserByNameSql = "SELECT id, user_name AS userName, pwd, create_time AS createTime, update_time AS updateTime FROM t_user WHERE user_name= ?;";

	//根据userId进行查询
	private static final String selectRolesByIdSql = "SELECT r.id, r.role_name AS roleName, r.create_time AS createTime, r.update_time AS updateTime FROM t_role r, t_user_role ur WHERE r.id = ur.role_id AND ur.user_id = ?;";

	@Autowired
	JdbcTemplate jdbcTemplate;

	@Override
	public int inserUser(String username, String pwd) {
		return jdbcTemplate.update(insertUserSql, username, pwd, username);
	}

	@Override
	public User selectByName(String username) {
		try {
			return jdbcTemplate.queryForObject(selectUserByNameSql, new Object[]{username}, new BeanPropertyRowMapper<User>(User.class));
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public List<Role> selectRolesByUserId(Long id) {
		return jdbcTemplate.query(selectRolesByIdSql, new Object[]{id}, new BeanPropertyRowMapper<Role>(Role.class));
	}

}
